import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import '../app_data_manager.dart';

class CourseImportService {
  static Future<bool> importCourses() async {
    try {
      print('开始导入课表...');
      
      if (Platform.isAndroid) {
        print('检查存储权限状态...');
        
        // 检查照片和视频权限（Android 13 及以上）
        var photosStatus = await Permission.photos.status;
        print('照片权限状态: $photosStatus');
        
        if (photosStatus.isDenied) {
          print('请求照片权限...');
          photosStatus = await Permission.photos.request();
          print('照片权限请求结果: $photosStatus');
          
          if (!photosStatus.isGranted) {
            print('照片权限被拒绝，打开应用设置...');
            await openAppSettings();
            return false;
          }
        }
        
        // 检查媒体权限（Android 13 及以上）
        var mediaStatus = await Permission.videos.status;
        print('媒体权限状态: $mediaStatus');
        
        if (mediaStatus.isDenied) {
          print('请求媒体权限...');
          mediaStatus = await Permission.videos.request();
          print('媒体权限请求结果: $mediaStatus');
          
          if (!mediaStatus.isGranted) {
            print('媒体权限被拒绝，打开应用设置...');
            await openAppSettings();
          return false;
          }
        }
      }
      
      // 选择文件
      print('开始选择文件...');
      final picker = ImagePicker();
      final XFile? result = await picker.pickMedia(
        requestFullMetadata: false, // 不请求完整的元数据
      );

      print('文件选择结果: ${result != null}');

      if (result == null) {
        print('未选择文件');
        return false;
      }

      // 检查文件扩展名
      if (!result.path.toLowerCase().endsWith('.ics')) {
        print('文件格式不正确，需要.ics文件');
        return false;
      }

      // 读取文件内容
      String filePath = result.path;
      print('选择的文件路径: $filePath');
      
      String content = await File(filePath).readAsString();
      print('文件内容长度: ${content.length}');
      print('文件内容预览: ${content.substring(0, content.length > 200 ? 200 : content.length)}');

      // 解析ics文件
      final events = _parseIcs(content);
      print('解析到的事件数量: ${events.length}');
      print('解析到的事件详情:');
      for (var event in events) {
        print('事件:');
        print('  名称: ${event['SUMMARY']}');
        print('  开始时间: ${event['DTSTART']}');
        print('  结束时间: ${event['DTEND']}');
        print('  地点: ${event['LOCATION']}');
        print('  重复规则: ${event['RRULE']}');
        print('  --------------------');
      }

      // 转换并存储课程信息
      List<Map<String, dynamic>> courses = [];
      for (var event in events) {
        try {
          final startTime = _parseDateTime(event['DTSTART']);
          final endTime = _parseDateTime(event['DTEND']);
          final rrule = _parseRRule(event['RRULE']);
          final name = event['SUMMARY'];
          final location = event['LOCATION'];
          
          if (startTime != null && endTime != null && name != null && name.isNotEmpty) {
            // 计算课程时长
            final duration = endTime.difference(startTime);
            
            // 如果没有重复规则，只添加一次
            if (rrule == null) {
              final course = {
                'name': name,
                'startTime': startTime.toIso8601String(),
                'endTime': endTime.toIso8601String(),
                'location': location ?? '',
              };
              courses.add(course);
              print('添加单次课程:');
              print('  课程名称: ${course['name']}');
              print('  开始时间: ${course['startTime']}');
              print('  结束时间: ${course['endTime']}');
              print('  上课地点: ${course['location']}');
              print('  --------------------');
            } else {
              // 处理重复规则
              final frequency = rrule['frequency'];
              final count = rrule['count'] ?? 1;
              final interval = rrule['interval'] ?? 1;
              
              if (frequency == 'WEEKLY') {
                // 每周重复
                for (int i = 0; i < count; i++) {
                  final weekOffset = (i * interval).toInt();
                  final courseStartTime = startTime.add(Duration(days: weekOffset * 7));
                  final courseEndTime = courseStartTime.add(duration);
                  
                  final course = {
                    'name': name,
                    'startTime': courseStartTime.toIso8601String(),
                    'endTime': courseEndTime.toIso8601String(),
                    'location': location ?? '',
                  };
                  courses.add(course);
                  
                  print('添加重复课程:');
                  print('  课程名称: ${course['name']}');
                  print('  开始时间: ${course['startTime']}');
                  print('  结束时间: ${course['endTime']}');
                  print('  上课地点: ${course['location']}');
                  print('  第 ${i + 1} 次重复');
                  print('  --------------------');
                }
              }
            }
          } else {
            print('跳过无效课程:');
            print('  名称: $name');
            print('  开始时间: $startTime');
            print('  结束时间: $endTime');
            print('  --------------------');
          }
        } catch (e) {
          print('转换课程失败: $e');
          print('事件数据: $event');
        }
      }

      print('转换后的课程总数: ${courses.length}');

      // 保存课程信息
      await AppDataManager().saveCourseTable(courses);
      print('课表导入完成');
      return true;
    } catch (e, stackTrace) {
      print('导入课表失败: $e');
      print('错误堆栈: $stackTrace');
      return false;
    }
  }

  static DateTime? _parseDateTime(String? dateTimeStr) {
    if (dateTimeStr == null || dateTimeStr.isEmpty) return null;
    
    try {
      // 尝试解析格式：20250217T143000
      if (dateTimeStr.length >= 15) {
        final year = int.parse(dateTimeStr.substring(0, 4));
        final month = int.parse(dateTimeStr.substring(4, 6));
        final day = int.parse(dateTimeStr.substring(6, 8));
        final hour = int.parse(dateTimeStr.substring(9, 11));
        final minute = int.parse(dateTimeStr.substring(11, 13));
        return DateTime(year, month, day, hour, minute);
      }
    } catch (e) {
      print('解析日期时间失败: $dateTimeStr, 错误: $e');
    }
    return null;
  }

  static Map<String, dynamic>? _parseRRule(String? rruleStr) {
    if (rruleStr == null || rruleStr.isEmpty) return null;
    
    try {
      final parts = rruleStr.split(';');
      final rrule = <String, dynamic>{};
      
      for (var part in parts) {
        final keyValue = part.split('=');
        if (keyValue.length == 2) {
          final key = keyValue[0];
          final value = keyValue[1];
          
          switch (key) {
            case 'FREQ':
              rrule['frequency'] = value;
              break;
            case 'COUNT':
              rrule['count'] = int.parse(value);
              break;
            case 'INTERVAL':
              rrule['interval'] = int.parse(value);
              break;
            case 'BYDAY':
              rrule['byDay'] = value.split(',');
              break;
          }
        }
      }
      
      return rrule;
    } catch (e) {
      print('解析重复规则失败: $rruleStr, 错误: $e');
      return null;
    }
  }

  static List<Map<String, String>> _parseIcs(String content) {
    List<Map<String, String>> events = [];
    final lines = content.split('\n');
    Map<String, String>? currentEvent;
    
    for (var line in lines) {
      line = line.trim();
      if (line.startsWith('BEGIN:VEVENT')) {
        currentEvent = {};
      } else if (line.startsWith('END:VEVENT')) {
        if (currentEvent != null) {
          events.add(currentEvent);
          currentEvent = null;
        }
      } else if (currentEvent != null) {
        final parts = line.split(':');
        if (parts.length == 2) {
          final key = parts[0].split(';')[0].trim();
          final value = parts[1].trim();
          currentEvent[key] = value;
        }
      }
    }
    
    return events;
  }
} 